import React, {useContext, useCallback, useState, useRef} from 'react';
import {Link} from 'react-router-dom';
import {Form, Input, FormGroup, Label, Row, Col, Button, FormFeedback} from 'reactstrap';

import {AuthContext} from '../auth-context';

const Reg = () => {

  const {register} = useContext(AuthContext);

  const [mail, setMail] = useState('');
  const [fail, setFail] = useState(false);
  const [pass, setPass] = useState('');
  const [conf, setConf] = useState('');

  // const {register} = useContext(AuthContext);

  const confRef = useRef();

  const submitRegister = async (e) => {
    e.preventDefault();
    const res = await register(mail, pass);
    if (!res.ok) {
      setFail(true);
    }
  }

  const updateMail = (e) => {
    setMail(e.target.value);
  }

  const updatePass = (e) => {
    setPass(e.target.value);
  }

  const updateConf = (e) => {
    setConf(e.target.value);
  }

  return (
    <div style={{}}>
      <Form onSubmit={submitRegister}>
        <FormGroup>
          <Label for="mail" sm={2}>Email</Label>
          <Input id="mail" type="email" placeholder="Email address as Username" value={mail} onInput={updateMail} invalid={fail}/>
          <FormFeedback>Username already taken</FormFeedback>
        </FormGroup>
        <Row>
          <Col md={6}>
            <FormGroup>
              <Label for="pass" sm={2} style={{width: '100%'}}>Password</Label>
              <Input id="pass" type="password" placeholder="Password" value={pass} onInput={updatePass}/>
            </FormGroup>
          </Col>
          <Col md={6}>
            <FormGroup>
              <Label for="pass" sm={2} style={{width: '100%'}}>Confirm Password</Label>
              <Input id="conf" type="password" placeholder="Confirm Password" value={conf} onInput={updateConf} ref={confRef} invalid={pass !== conf}/>
              <FormFeedback>Two password inputs mismatch</FormFeedback>
            </FormGroup>
          </Col>
        </Row>
        <Row>
          <Col md={6}>
            <FormGroup>
              <Label for='login' sm={2} style={{width: '100%'}}>Register new account</Label>
              <Button id='login' type="submit">Register</Button>
            </FormGroup>
          </Col>
          <Col md={6}>
            <FormGroup>
              <Label for='reg' sm={2}  style={{width: '100%'}}>Remember the password?</Label>
              <Link to="/login">
                <Button type="button" style={{display: 'block'}}>
                  <span>Go to Login</span>
                </Button>
              </Link>
            </FormGroup>
          </Col>
        </Row>
      </Form>
    </div>
  );
};

export default Reg;